package web.servlet.profilePhoto;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.LyyBaseResponse;
import domain.ProfilePhoto;
import service.ProfilePhotoService;
import service.impl.ProfilePhotoServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet("/addProfilePhoto")
public class AddProfilePhotoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        String userId = request.getParameter("userId");
        String pictureStr = request.getParameter("pictureStr");
        ProfilePhotoService service=new ProfilePhotoServiceImpl();
        ProfilePhoto profilePhoto = new ProfilePhoto();
        profilePhoto.setUploadTime(new Date());
        Exception exception=null;
        boolean flag=false;
        try {
            profilePhoto.setUserId(Integer.parseInt(userId));
            profilePhoto.setPictureStr(pictureStr);
            try {
                flag=service.addPhoto(profilePhoto);
            } catch (Exception e) {
                exception=e;
                e.printStackTrace();
            }
        } catch (Exception e) {
            exception=e;
            e.printStackTrace();
        }
        LyyBaseResponse lyyBaseResponse=new LyyBaseResponse();
        if(exception!=null){
            lyyBaseResponse.setErrMsg(exception.getMessage());
            lyyBaseResponse.setStatus(0);
        }else {
            if(!flag){
                lyyBaseResponse.setErrMsg("添加头像失败！");
                lyyBaseResponse.setStatus(0);
            }
        }
        ObjectMapper objectMapper=new ObjectMapper();
        objectMapper.writeValue(response.getOutputStream(),lyyBaseResponse);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
